const Router = require("@koa/router");
const router = new Router();
const {
  modelAdministrator,
  modelDailyrecom,
  provinceSchema,
  modelFourTravel,
} = require("@/models/collection-pc");
const {
  Adminregister,
  ModifyuserInfo,
  Dailyrecom,
  Serchtravel,
  Resreturn,
  CompanionDatails,
  UploadfourTravel,
  ModifyfourTravel,
} = require("@/config/valiData");
const { Auth } = require("@/token/auth");
const crypto = require("crypto");
const { gentoken } = require("@/token/jwt");
const { upload, cosUpdate } = require("@/cos/cos");
const moment = require("moment");
const fs = require("fs");
moment.locale("zh-cn");

const {
  modelUser,
  modelArticle,
  modelConcern,
} = require("@/models/collection");

const { looKup, looKupRecommend } = require("@/config/lookup");

//注册管理员账号
router.post("/adminRegister", async (ctx) => {
  const { mobile, password } = ctx.request.body;
  Adminregister(mobile, password);
  const res = await modelAdministrator.find({ mobile }).lean();
  if (res.length > 0) {
    ctx.send("该账号已存在", 422);
    return false;
  } else {
    //创建哈希对象
    const hash = crypto.createHash("sha256").update(password);
    //生成哈希值
    const passwordHash = hash.digest("hex");
    await modelAdministrator.create({
      mobile,
      password: passwordHash,
    });
    ctx.send("注册成功", 200);
  }
});

//管理员登录
router.post("/adminLogin", async (ctx) => {
  // 1. 从请求体中解构获取手机号和密码
  const { mobile, password } = ctx.request.body;

  // 2. 调用管理员注册验证函数
  Adminregister(mobile, password);

  // 3. 密码加密处理
  const hash = crypto.createHash("sha256").update(password); // 创建 SHA256 哈希对象
  const passwordHash = hash.digest("hex"); // 生成十六进制格式的哈希值

  // 4. 查询数据库
  const res = await modelAdministrator
    .find(
      { mobile, password: passwordHash }, // 查询条件
      { mobile: false } // 投影，不返回 mobile 字段
    )
    .lean(); // 转换为普通 JavaScript 对象

  // 5. 处理查询结果
  if (res.length > 0) {
    // 生成包含用户令牌的对象
    const token = { user_Token: gentoken(res[0].admin_uid) };
    // 返回成功响应，合并用户信息和令牌
    ctx.send("SUCCESS", 200, { ...res[0], ...token });
  } else {
    // 返回错误响应
    ctx.send("账号或密码错误", 422);
  }
});

//图片上传接口
router.post("/imageUpload", upload.array("file", 6), async (ctx) => {
  const res = await cosUpdate(ctx.files);
  ctx.send("SUCCESS", 200, res[0]);
});

//更新管理员头像和昵称
router.post("/modifyUserInfor", new Auth().m, async (ctx) => {
  const { _id, avatarUrl, nickname } = ctx.request.body;
  ModifyuserInfo(_id, nickname, avatarUrl);
  console.log(avatarUrl);

  await modelAdministrator.findByIdAndUpdate(
    { _id },
    {
      nickname,
      avatarUrl,
    }
  );

  ctx.send("更新成功", 200);
});

//上传每天推荐
router.post("/dailyRecom", new Auth().m, async (ctx) => {
  const { imageUrl, title, address, color } = ctx.request.body;
  Dailyrecom(imageUrl, title, address, color);
  await modelDailyrecom.create({ imageUrl, title, address, color });
  ctx.send("上传成功", 200);
});

//导入省市到数据库  仅限一次使用：后台
router.get("/insert-database", async (ctx) => {
  const citydata = fs.readFileSync(
    "C:/Users/24599/Desktop/学习资料/lvyou-node/china.json"
  );
  const res = JSON.parse(citydata);
  await provinceSchema.insertMany(res); //插入数据
});

//搜索省市数据
router.get("/china-data", new Auth().m, async (ctx) => {
  const { keywords } = ctx.query;
  Serchtravel(keywords);
  if (keywords.trim() === "") {
    ctx.send("SUCCESS", 200, []);
    return false;
  }
  const regex = new RegExp(keywords, "i");
  const res = await provinceSchema.aggregate([
    //第一阶段：查询,
    {
      $match: {
        $or: [
          { provinceName: regex }, //匹配省
          { "citys.cityName": regex }, //匹配市
        ],
      },
    },
    //第二阶段：分组
    {
      $project: {
        //可以指定返回前端哪些字段，可以重组
        _id: 0,
        provinceName: 1,
        citys: {
          $filter: {
            //用户筛选符合条件的城市
            input: "$citys", //表示对哪个字段进行处理
            as: "city", //指定变量值
            cond: {
              //进行逻辑处理
              $or: [
                //匹配市
                { $regexMatch: { input: "$$city.cityName", regex: regex } },
                { $regexMatch: { input: "$provinceName", regex: regex } },
              ],
              //$regexMatch:正则匹配
            },
          },
        },
      },
    },
  ]);
  ctx.body = res;
});

//获取每日推荐
router.get("/gainDailyRecom", new Auth().m, async (ctx) => {
  const { page } = ctx.query;
  Resreturn(page);
  const res = await modelDailyrecom
    .find({}, { timestamp: false })
    .sort({ timestamp: -1 })
    .skip((page - 1) * 6)
    .limit(6);
  //获取数据总条数
  const count = await modelDailyrecom.countDocuments();
  const resData = { data: res, count };
  ctx.send("SUCCESS", 200, resData);
});

//删除每日推荐
router.get("/deleteDailyRecom", new Auth().m, async (ctx) => {
  const { _id } = ctx.query;
  CompanionDatails(_id);
  await modelDailyrecom.deleteMany({ _id });
  ctx.send("SUCCESS", 200);
});

//获取所有用户的游记：用作关联推荐
router.get("/allUserTravel", new Auth().m, async (ctx) => {
  const { page } = ctx.query;
  Resreturn(page);
  const res = await modelArticle.aggregate([
    { $sort: { time_stamp: -1 } }, //按创建时间倒序查询
    { $skip: (page - 1) * 10 },
    { $limit: 10 },
    looKup().model_user, //关联用户表
    {
      $project: {
        _id: 1,
        title: 1,
        address: 1,
        time: 1,
        "author_data.nickname": 1,
      },
    },
  ]);
  //获取数据总条数
  const count = await modelArticle.countDocuments();
  const resObj = { data: res, count };
  ctx.send("SUCCESS", 200, resObj);
});

//提交4个推荐
router.post("/uploadFourTravel", new Auth().m, async (ctx) => {
  const { imageUrl, travel_id } = ctx.request.body;
  UploadfourTravel(imageUrl, travel_id);
  await modelFourTravel.create({ imageUrl, travel_id });
  ctx.send("SUCCESS", 200);
});

//获取四个推荐游记表
router.get("/gainRecomTravel", new Auth().m, async (ctx) => {
  const res = await modelFourTravel.aggregate([
    { $sort: { timestamp: -1 } }, //按创建时间倒序查询
    looKupRecommend().model_Article,
    looKupRecommend().model_reco_user,
    { $unwind: "$articleData" },
    { $unwind: "$userData" },
    {
      $project: {
        _id: 1,
        imageUrl: 1,
        title: "$articleData.title",
        time: 1,
        travel_id: 1,
        articltTime: "$articleData.time",
        nickname: "$userData.nickname",
      },
    },
  ]);
  ctx.send("SUCCESS", 200, res);
});

//修改更新四个游记
router.post("/modifyRecomTravel", new Auth().m, async (ctx) => {
  const { _id, imageUrl, travel_id } = ctx.request.body;
  ModifyfourTravel(_id, imageUrl, travel_id);
  await modelFourTravel.findByIdAndUpdate({ _id }, { imageUrl, travel_id });
  ctx.send("SUCCESS", 200);
});

//删除四个游记
router.get("/deleteRecomTravel", new Auth().m, async (ctx) => {
  const { _id } = ctx.query;
  CompanionDatails(_id);
  await modelFourTravel.deleteMany({ _id });
  ctx.send("SUCCESS", 200);
});

// 邮游记管理：获取全部游记
router.get("/travelManaGement", new Auth().m, async (ctx) => {
  const { page } = ctx.query;
  Resreturn(page);
  const res = await modelArticle.aggregate([
    { $sort: { time_stamp: -1 } }, //按创建时间倒序查询
    { $skip: (page - 1) * 10 },
    { $limit: 10 },
    looKup().model_user,
    {
      $project: {
        _id: 1,
        title: 1,
        content: 1,
        image: 1,
        videoUrl: 1,
        fileType: 1,
        city: 1,
        address: 1,
        province: 1,
        time: 1,
        cover_image: 1,
        "author_data.avatarUrl": 1,
        "author_data.nickname": 1,
      },
    },
  ]);
  const count = await modelArticle.countDocuments();
  const resObj = { data: res, count };
  ctx.send("SUCCESS", 200, resObj);
});

// 用户管理：获取所有用户信息
router.get("/allUserInfor", new Auth().m, async (ctx) => {
  const { page } = ctx.query;
  Resreturn(page);
  const res = await modelUser.aggregate([
    { $skip: (page - 1) * 10 },
    { $limit: 10 },
    {
      $lookup: {
        //关联游记表，获取游记总数
        from: modelArticle.collection.name,
        localField: "uid",
        foreignField: "author_uid",
        as: "articleQuantity",
      },
    },
    {
      $lookup: {
        //关联关注表，获取粉丝数
        from: modelConcern.collection.name,
        localField: "uid",
        foreignField: "im_concerned_uid",
        as: "concernQuantity",
      },
    },
    {
      $project: {
        _id: 1,
        avatarUrl: 1,
        nickname: 1,
        uid: 1,
        mobile: 1,
        //计算粉丝数量
        concernQuantity: { $size: "$concernQuantity" },
        //计算发表文章数量
        articleQuantity: { $size: "$articleQuantity" },
      },
    },
  ]);
  const count = await modelUser.countDocuments();
  const resObj = { data: res, count };
  ctx.send("SUCCESS", 200, resObj);
});

module.exports = router.routes();
